<template>
  <tab-bar :active="2">
    <!-- 小程序状态栏 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- #endif -->
    
    <view class="container">
      <!-- 顶部标题栏 -->
      <view class="header">
        <view class="title">消息</view>
        <view class="clear-btn" @click="clearAll">
          <image src="/static/Images/notice/Qingchu.png" class="clear-icon"></image>
        </view>
      </view>
      
      <!-- 推送通知栏 -->
      <!-- #ifdef APP-PLUS || MP-WEIXIN -->
      <view class="notification-bar">
        <view class="notification-content">
          <image src="/static/Images/notice/Tongzhi.png" class="notification-icon"></image>
          <text class="notification-text">开启推送通知，消息不再错过</text>
        </view>
        <view class="notification-actions">
          <view class="open-btn" @click="openNotification">开启</view>
          <view class="close-btn" @click="closeNotification">
            <image src="/static/Images/notice/Guanbi.png" class="close-icon"></image>
          </view>
        </view>
      </view>
      <!-- #endif -->
      
      <!-- 消息列表 -->
      <view class="message-list">
        <!-- 系统公告通知 -->
        <view class="message-item" @click="goToNoticeList">
          <view class="message-left">
            <view class="avatar-container orange">
              <image src="/static/Images/notice/Lingdan.png" class="avatar-icon"></image>
              <view class="red-dot" v-if="systemNoticeCount > 0">{{ systemNoticeCount }}</view>
            </view>
            <view class="message-info">
              <view class="message-title">系统公告通知</view>
              <view class="message-desc">{{ systemLatestDesc || '这里是最新消息的展示，展示最新的消息即可...' }}</view>
            </view>
          </view>
          <view class="message-right">
            <view class="message-time">{{ systemLatestTime || '06-23' }}</view>
          </view>
        </view>
        
        <!-- 平台站内短信 -->
        <view class="message-item" @click="goToTextList">
          <view class="message-left">
            <view class="avatar-container green">
              <image src="/static/Images/notice/Xinxi.png" class="avatar-icon"></image>
              <view class="red-dot" v-if="textNoticeCount > 0">{{ textNoticeCount }}</view>
            </view>
            <view class="message-info">
              <view class="message-title">平台站内短信</view>
              <view class="message-desc">{{ textLatestDesc || '这里是最新消息的展示，展示最新的短信即可...' }}</view>
            </view>
          </view>
          <view class="message-right">
            <view class="message-time">{{ textLatestTime || '06-23' }}</view>
          </view>
        </view>
        
        <!-- 交易通知 -->
        <view class="message-item" @click="goToTradeNotice">
          <view class="message-left">
            <view class="avatar-container blue">
              <image src="/static/Images/notice/Jiaoyi.png" class="avatar-icon"></image>
              <view class="red-dot" v-if="tradeNoticeCount > 0">{{ tradeNoticeCount }}</view>
            </view>
            <view class="message-info">
              <view class="message-title">交易通知</view>
              <view class="message-desc">{{ tradeLatestDesc || '交易订单消息通知' }}</view>
            </view>
          </view>
          <view class="message-right">
            <view class="message-time">{{ tradeLatestTime || '14:25' }}</view>
          </view>
        </view>
      </view>
      
    </view>
    

  </tab-bar>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import TabBar from '@/components/TabBar.vue'
import { indexApi } from '@/utils/api'
import { userStorage } from '@/utils/storage'

// 状态栏高度
const statusBarHeight = ref(0)

// 登录状态检查
const isLoggedIn = computed(() => {
  return userStorage.isLoggedIn()
})

// 响应式数据
const systemNoticeCount = ref(0)
const textNoticeCount = ref(0)
const tradeNoticeCount = ref(0)

const systemLatestDesc = ref('')
const systemLatestTime = ref('')
const textLatestDesc = ref('')
const textLatestTime = ref('')
const tradeLatestDesc = ref('')
const tradeLatestTime = ref('')



// 获取通知列表
const fetchNoticeList = async () => {
  try {
    // 检查登录状态
    if (!isLoggedIn.value) {
      return
    }
    
    // 分三类分别请求，避免后端必须传 type 导致的错误
    const page = 1
    const size = 10
    const [sysRes, textRes, tradeRes] = await Promise.all([
      indexApi.getNoticeList(1, page, size),
      indexApi.getNoticeList(2, page, size),
      indexApi.getNoticeList(3, page, size)
    ])

    const sysData = sysRes?.data || []
    const textData = textRes?.data || []
    const tradeData = tradeRes?.data || []

    // 计算未读消息数量（is_read 为 0 的消息）
    systemNoticeCount.value = sysData.filter(item => item.is_read === 0).length
    textNoticeCount.value = textData.filter(item => item.is_read === 0).length
    tradeNoticeCount.value = tradeData.filter(item => item.is_read === 0).length

    if (sysData.length > 0) {
      const latest = sysData[0]
      systemLatestDesc.value = latest.desc || latest.title || ''
      systemLatestTime.value = formatTime(latest.create_time)
    } else {
      systemLatestDesc.value = ''
      systemLatestTime.value = ''
    }

    if (textData.length > 0) {
      const latest = textData[0]
      textLatestDesc.value = latest.desc || latest.title || ''
      textLatestTime.value = formatTime(latest.create_time)
    } else {
      textLatestDesc.value = ''
      textLatestTime.value = ''
    }

    if (tradeData.length > 0) {
      const latest = tradeData[0]
      tradeLatestDesc.value = latest.desc || latest.title || ''
      tradeLatestTime.value = formatTime(latest.create_time)
    } else {
      tradeLatestDesc.value = ''
      tradeLatestTime.value = ''
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    uni.showToast({ title: `获取消息失败：${error.message || error}`, icon: 'none' })
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  try {
    const date = new Date(timeStr)
    const now = new Date()
    
    // 如果是今天，显示时:分
    if (date.toDateString() === now.toDateString()) {
      return date.toTimeString().slice(0, 5)
    }
    
    // 如果是今年，显示月-日
    if (date.getFullYear() === now.getFullYear()) {
      return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 其他情况显示年-月-日
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  } catch (error) {
    return timeStr.slice(5, 10) // 回退显示 MM-DD
  }
}

// 方法
const clearAll = async () => {
  try {
    // 检查登录状态
    if (!isLoggedIn.value) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 显示确认对话框
    const result = await new Promise((resolve) => {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有未读消息吗？',
        success: (res) => {
          resolve(res.confirm)
        },
        fail: () => {
          resolve(false)
        }
      })
    })

    if (!result) {
      return
    }

    // 显示加载提示
    uni.showLoading({
      title: '清空中...'
    })

    // 调用批量清除接口
    const token = userStorage.getToken()
    await indexApi.setAllNoticeRead(token)

    uni.hideLoading()
    uni.showToast({
      title: '已清空所有未读消息',
      icon: 'success'
    })

    // 刷新消息列表
    await fetchNoticeList()

  } catch (error) {
    console.error('批量清空消息失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: '清空失败，请稍后再试',
      icon: 'none'
    })
  }
}

const openNotification = () => {
  console.log('开启推送通知')
}

const closeNotification = () => {
  console.log('关闭通知栏')
}

const goToNoticeList = () => {
  uni.navigateTo({
    url: '/pages/notice/noticelist'
  })
}

const goToTextList = () => {
  uni.navigateTo({
    url: '/pages/notice/textlist'
  })
}

const goToTradeNotice = () => {
  console.log('跳转到交易通知')
  uni.navigateTo({
    url: '/pages/notice/tradelist'
  })
}



// 页面加载时获取通知列表
onMounted(() => {
  // 获取状态栏高度（仅小程序）
  // #ifdef MP-WEIXIN
  const systemInfo = uni.getSystemInfoSync()
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  // 状态栏高度 + 胶囊按钮高度 + 额外间距
  statusBarHeight.value = (systemInfo.statusBarHeight || 0) + (menuButtonInfo.height || 32) + 8
  // #endif
  
  fetchNoticeList()
})

// 页面显示时获取数据（仅在从其他页面返回时刷新）
onShow(() => {
  // 只有在页面已经挂载后才刷新数据，避免重复请求
  if (statusBarHeight.value > 0) {
    fetchNoticeList()
  }
})
</script>

<style scoped>
/* 小程序状态栏样式 */
.status-bar {
  width: 100%;
  background: linear-gradient(180deg, #FF7B80 0%, rgba(244,234,234,0) 100%);
}

.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  width: 752rpx;
  margin: 0 auto;
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  background-color: #ffffff;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #333333;
}

.clear-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-icon {
  width: 20px;
  height: 20px;
}

.notification-bar {
  background: linear-gradient(90deg, #ffebee 0%, #fce4ec 100%);
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.notification-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.notification-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
}

.notification-text {
  font-size: 14px;
  color: #333333;
}

.notification-actions {
  display: flex;
  align-items: center;
}

.open-btn {
  background-color: #ff4444;
  color: #ffffff;
  font-size: 12px;
  padding: 4px 12px;
  border-radius: 12px;
  margin-right: 8px;
}

.close-btn {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-icon {
  width: 16px;
  height: 16px;
}

.message-list {
  background-color: #ffffff;
  margin-top: 8px;
}

.message-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.message-item:last-child {
  border-bottom: none;
}

.message-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.avatar-container {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.avatar-container.orange {
  background-color: #ff9500;
}

.avatar-container.green {
  background-color: #00c896;
}

.avatar-container.blue {
  background-color: #007aff;
}

.avatar-icon {
  width: 100%;
  height: 100%;
}

.red-dot {
  position: absolute;
  top: -1rem;
  right: -0.5rem;
  min-width: 1.2rem;
  height: 1.2rem;
  background-color: #ff4444;
  border-radius: 0.8rem;
  border: 2px solid #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #ffffff;
  font-weight: 500;
  padding: 0 4px;
  box-sizing: border-box;
}

.message-info {
  flex: 1;
}

.message-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 4px;
}

.message-desc {
  font-size: 14px;
  color: #999999;
  line-height: 1.4;
}

.message-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-time {
  font-size: 12px;
  color: #999999;
}

.footer-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 8px 0 20px 0;
  border-top: 1px solid #f0f0f0;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.nav-icon-bg {
  width: 32px;
  height: 32px;
  background-color: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 4px;
}

.nav-icon {
  width: 20px;
  height: 20px;
  margin-bottom: 4px;
}

.nav-icon.active {
  width: 16px;
  height: 16px;
  margin-bottom: 0;
}

.nav-text {
  font-size: 10px;
  color: #999999;
}

.nav-text.active {
  color: #ff4444;
}
</style>